import React from 'react';
import {Form, Row, Col, Button, message, Menu, Divider, Input, TimePicker, Checkbox} from 'antd';
import {sessionManager} from '../../utils/sessionStorage';
import {withRouter} from 'react-router-dom'
import {injectIntl} from 'react-intl';
import axios from 'axios';
import moment from 'moment';
import PickCity from '../../components/pickCity/pickCity';
import SCModal from '../../components/pickCity/SCModal';
import ChooseSite from '../../components/Amap/ChooseSite'

const FormItem = Form.Item;
const createForm = Form.create;

@withRouter
class BaseInfo extends React.Component {
    constructor(props) {
        super(props);
        this.common = this.props.intl.messages.common;
        this.state = {
            baseInfo: sessionManager.get('selectStuGroup'),
            info: {},
            local: [],
            visible: false,
            mapInfo:{}
        }
    }

    componentDidMount() {
        this.getBaseInfo();
    }

    openMap = () => {
        this.setState({
            visible: true,
        })
    };

    getMapInfo=(data)=>{
        this.setState({
            mapInfo:data
        },()=>{
            this.changePos()
        })
    };

    changePos=()=>{
        console.log(this.state.mapInfo);
        const {setFieldsValue} = this.props.form;
        setFieldsValue({'gisGcj02Lat':this.state.mapInfo.position.lat});
        setFieldsValue({'gisGcj02Lng':this.state.mapInfo.position.lng});
    };

    handleCancel=()=>{
        this.setState({
            visible: false,
        })
    };


    getBaseInfo = async () => {
        try {
            const info = await axios.get('/api/stubGroup/info', {params:{stubGroupId: this.state.baseInfo.id},loading:true});
            this.setState({
                info: info.data
            });
            const province = axios.post('api/province/option', {...{type: 1}});
            const city = axios.post('api/city/option', {...{type: 1}});
            const region = axios.post('api/region/option', {...{type: 1}});
            const [provinceRes, cityRes, regionRes] = await Promise.all([province, city, region]);
            let localProvince = provinceRes.data.filter((k, v) => (k.id === info.data.province));
            let localCity = cityRes.data.filter((k, v) => (k.id === info.data.city));
            let localRegion = regionRes.data.filter((k, v) => (k.id === info.data.region));
            this.setState({
                local: [...localProvince, ...localCity, ...localRegion]
            })
        } catch (e) {
            console.log(e)
        }

    }
    ;

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!!err) {
                console.log('手机登陆 ', values);
                return;
            }
            values.region = values.region ? values.region[values.region.length - 1] : this.state.local[this.state.local.length - 1].id;
            values.serviceStartTime = values.serviceStartTime.format('HH:mm');
            values.serviceEndTime = values.serviceEndTime.format('HH:mm');
            values.serviceTime = `${values.serviceStartTime}-${values.serviceEndTime}`;
            if (values.parkingFree === true) {
                values.parkingFree = 1
            }
            if (values.parkingFree === false) {
                values.parkingFree = 0
            }
            delete values.serviceStartTime;
            delete values.serviceTime;
            values.id = this.state.baseInfo.id;
            axios.get('/api/stubGroup/update', {params: values, loading: true}).then(res => {
                if (res && res.data) {
                    message.success(`${this.common.OperateSuccessfully}，修改信息将在几分钟后更新`);
                    this.props.history.goBack()
                }
            })
        });
    };


    render() {
        const flag = this.state.baseInfo.isOwned == 0 ? false : true;
        const formItemLayout = {
            labelCol: {
                xl: {span: 4},
                xxl: {span: 4},
            },
            wrapperCol: {
                xl: {span: 18},
                xxl: {span: 20},
            },
        };
        const formItemLayout2 = {
            labelCol: {
                xl: {span: 8},
                xxl: {span: 8},
            },
            wrapperCol: {
                xl: {span: 16},
                xxl: {span: 16},
            },
        };
        const formItemLayout3 = {
            labelCol: {
                xl: {span: 14},
                xxl: {span: 12},
            },
            wrapperCol: {
                xl: {span: 10},
                xxl: {span: 12},
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xl: {
                    span: 20,
                    offset: 4,
                },
            },
        };
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <Col xl={15} xxl={8}>
                        <form form={this.props.form}>
                            <FormItem
                                {...formItemLayout}
                                label="电站名称"
                            >
                                {getFieldDecorator(`name`, {initialValue: this.state.info.name})(
                                    <Input disabled={flag}/>
                                )}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label="所在地"
                            >
                                {getFieldDecorator(`region`,)(
                                    <PickCity level1={{url:'/api/province/option',params:{type:1}}} level2={{url:'/api/city/option',params:{type:1}}} level3={{url:'/api/region/option',params:{type:1}}}
                                              placeholder={this.state.local.map((k) => (k.name)).join('/')}
                                              disabled={flag}/>
                                )}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label="详细地址"
                            >
                                {getFieldDecorator(`address`, {initialValue: this.state.info.address})(
                                    <Input disabled={flag}/>
                                )}
                            </FormItem>
                            <Row gutter={24}>
                                <Col span={10}>
                                    <FormItem
                                        {...formItemLayout2}
                                        label="经度"
                                    >
                                        {getFieldDecorator(`gisGcj02Lat`, {initialValue: this.state.info.gisGcj02Lat})(
                                            <Input disabled={flag}/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={10}>
                                    <FormItem
                                        {...formItemLayout2}
                                        label="纬度"
                                    >
                                        {getFieldDecorator(`gisGcj02Lng`, {initialValue: this.state.info.gisGcj02Lng})(
                                            <Input disabled={flag}/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={4}>
                                    <FormItem
                                    >
                                        <Button type="primary" shape="circle" icon={'environment-o'}
                                                onClick={this.openMap}/>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <FormItem
                                        {...formItemLayout2}
                                        label="服务时间"
                                    >
                                        {getFieldDecorator(`serviceStartTime`, {initialValue: this.state.info.serviceTime ? moment(this.state.info.serviceTime.split('-')[0], 'HH:mm:ss') : undefined})(
                                            <TimePicker style={{marginRight: 34}} disabled={flag}/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={10}>
                                    <FormItem
                                    >
                                        {getFieldDecorator(`serviceEndTime`, {initialValue: this.state.info.serviceTime ? moment(this.state.info.serviceTime.split('-')[1], 'HH:mm:ss') : undefined})(
                                            <TimePicker style={{marginRight: 34}} disabled={flag}/>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <FormItem
                                {...formItemLayout}
                                label="车位描述	"
                            >
                                {getFieldDecorator(`parkingInfo`, {initialValue: this.state.info.parkingInfo})(
                                    <Input disabled={flag}/>
                                )}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label="车位引导"
                            >
                                {getFieldDecorator(`stubGroupInfo`, {initialValue: this.state.info.stubGroupInfo})(
                                    <Input disabled={flag}/>
                                )}
                            </FormItem>
                            <Row>
                                <Col xl={7} xxl={8}>
                                    <FormItem
                                        {...formItemLayout3}
                                        style={{whiteSpace: 'nowrap'}}
                                        label="停车费用"
                                    >
                                        {getFieldDecorator('parkingFree', {
                                            valuePropName: 'checked',
                                            initialValue: this.state.info.parkingFree
                                        })(
                                            <Checkbox disabled={flag}>免费</Checkbox>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col xl={15} xxl={16}>
                                    <FormItem
                                    >
                                        {getFieldDecorator(`parkingFeeInfo`, {initialValue: this.state.info.parkingFeeInfo})(
                                            <Input disabled={flag}/>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <FormItem
                                {...formItemLayout}
                                label="电站图片"
                            >
                                <div style={{display: 'flex'}}>
                                    {this.state.info.imgUrls && this.state.info.imgUrls.map((k) => {
                                        return <img key={k} src={k} className={'stubPics'}/>
                                    })}
                                </div>
                            </FormItem>
                            <Divider/>
                            <FormItem
                                {...tailFormItemLayout}
                            >
                                {!flag && <Button type={'primary'} onClick={this.handleSubmit}>保存</Button>}
                            </FormItem>
                        </form>
                    </Col>
                </Row>
                <SCModal visible={this.state.visible} handleCancel={this.handleCancel}>
                    <ChooseSite position={[this.state.info.gisGcj02Lng,this.state.info.gisGcj02Lat]} handleCancel={this.handleCancel} getMapInfo={this.getMapInfo}/>
                </SCModal>
            </div>
        )
    }
}

BaseInfo = createForm()(BaseInfo);
export default injectIntl(BaseInfo)